import React, { Component,Fragment } from 'react'
// antd
import {Form,Input,Button,Table,message,Modal,Select,Checkbox,Pagination,Row,Col} from "antd"
//api
import {GetList,getStream,Delete,addOne,editOne,totalRecords} from "../../api/video"
import { PlusOutlined,EditOutlined,DeleteOutlined,DownloadOutlined,PlaySquareOutlined,SearchOutlined  } from '@ant-design/icons';
import PubSub from 'pubsub-js'
import flvjs from 'flv.js'
const { Option } = Select;

export default class VideoShow extends Component {
    state = {
        keyword:"",
        //请求参数
        limit: 10,
        offset: 0,
        id:"",
        selectedRowKeys: [],
        visible:false,
        visible_edit:false,
        visible_add:false,
        is_active:true,
        is_active_edit:true,
        total:0,
        // is_active_edit:true,
        columns:[
            {title: "编号",dataIndex:"id",key:"id"},
            {title: "视频名",dataIndex:"stream_name",key:"stream_name"},
            {title: "日期",dataIndex:"datetime",key:"datetime"},
            {title: "上传人编号",dataIndex:"user_id",key:"user_id"},//涉及多表联查，后续改动
            {
                title: "操作",
                dataIndex:"operation",
                key:"operation", 
                width:280,
                render: (text, rowData) => {
                    const mmm = this.timeFormatSeconds(rowData.datetime)
                    var date = new Date(mmm);
                    var time1 = date.getTime()/1000;
                    // var time2 = date.valueOf();
                    // console.log(time1)
                    var filename = `${rowData.stream_name}-${time1}.flv`
                    var path = `http://www.dpl402.site:2180/${filename}`
                    // console.log(path)
                    return (
                        <div className="inline-button">
                            <Button type="primary" 
                            onClick={()=> this.onHanderEdit(rowData.stream_name,rowData.datetime,rowData.user_id)}
                            icon={<PlaySquareOutlined />} 
                            >
                                播放
                            </Button>

                            <Button onClick={() => this.onHanderDelete(rowData.id)} icon={<DeleteOutlined />} >删除</Button>&nbsp;

                            <a href={path} icon={<DownloadOutlined />} >下载</a>
                            
                            
                        </div>
                    )
                }
            },
        ],
        data:[]
    }
    /** 生命周期挂载完成 */
    componentDidMount(){
        this.loadData();
        this.totalrecords(); 
    }
    // shouldComponentUpdate(){
    //     this.totalrecords();
    //     return true;
    // }
    /** 删除 */
    onHanderDelete = (id) => {
        this.setState({
            visible:true,
            id:id,
        })
        
    }
    /** 删除弹窗,点击确认删除，调用的删除函数 */
    hideModal = ()=>{
        console.log(this.state)
        const {id:id} = this.state
        Delete(id).then(response => {
            const mess = "删除成功"
            // console.log(response.data)
            message.info(mess)
            this.setState({
                visible:false,
                id:"",
            })
            //请求数据
            this.loadData()
            this.totalrecords()
        })
    }
    timeFormatSeconds = (time)=> {
		var d = time ? new Date(time) : new Date();
		var year = d.getFullYear();
		var month = d.getMonth() + 1;
		var day = d.getDate();
		var hours = d.getHours();
		var min = d.getMinutes();
		var seconds = d.getSeconds();

		if (month < 10) month = '0' + month;
		if (day < 10) day = '0' + day;
		if (hours < 0) hours = '0' + hours;
		if (min < 10) min = '0' + min;
		if (seconds < 10) seconds = '0' + seconds;

		return (year + '-' + month + '-' + day + ' ' + hours + ':' + min + ':' + seconds);
    }

    /** 播放 */
    onHanderEdit = (stream_name,datetime,user_id) => {
        console.log(stream_name,datetime)
        const mmm = this.timeFormatSeconds(datetime)
        var date = new Date(mmm);
        var time1 = date.getTime()/1000;
        const time2 = mmm
        // var time2 = date.valueOf();
        console.log(time1)
        var filename = `${stream_name}-${time1}.flv`
        console.log(filename)
        // console.log(time2)
        // console.log(mmm)
        this.props.stream_name({stream_name,time1,time2,user_id,filename})
        this.props.switchForm('paly');
        // PubSub.publish("str_list",{stream_name,time1,time2,user_id,filename})
    }
    /** 加载页面 */
    
    loadData = () => {
        const requestData = {
            limit: this.state.limit,
            offset: this.state.offset
        }
         GetList(requestData).then(response =>{
            // console.log(response.data.length)
            const responseData = response.data//将获得的数据进行赋值加工
            console.log(responseData)
            responseData.map((item,index) => {
                const nn = this.timeFormatSeconds(item['datetime'])
                item['datetime'] = nn
                // console.log(item['datetime'],index)
            })
            if(responseData){

                this.setState({
                    data:responseData,
                    //total:response.data.length
                })
                // this.totalrecords();
            }
        }).catch(error =>{
            console.log(error);
        })         
    }

    totalrecords = ()=> {
        totalRecords().then(response => {
            // console.log(response.data)
            this.setState({
                total:response.data
            })
        }).catch(error=>{
            console.log(error.data)
        })
    }
        
    //根据视频名称搜索视频
     /** 搜索 */
     onFinish = (value)=>{
        const {videoname} = value
        console.log(videoname)
        if(videoname){
            getStream(videoname).then(response =>{
                const dataList = []
                const responseData = response.data
                console.log(responseData)
                // dataList.push(responseData)
                this.setState({
                    data:responseData,
                    total:responseData.length
                })
                   // this.totalRecords();
            }).catch( error =>{
                console.log(error)
                // this.setState({
                //     data:[]
                // })
            })
        }else{
            this.loadData();
        }      
    }

    
    /** 复选框 */
    onCheckeBox = (selectedRowKeys) => {
        this.setState({selectedRowKeys})
    }

    
    /**
     * 改变添加时is_active的状态
     */
    onChangeIs_active = (e)=>{
        this.setState({
            is_active:e.target.checked
        }) 
        // console.log("是否选中：",this.state.is_active)
    }
    /**
     * 改变编辑时is_active的状态
     */
    onChangeIs_active_edit = (e) => {
        this.setState({
            is_active_edit:e.target.checked
        })
    }
    /**
     * 当前页码
     */
    onChangeCurrentPage = (value) => {
        // console.log(value)
        const {limit} =this.state
        this.setState({
            offset:limit*(value-1),
        },()=>{
            // console.log(this.state.offset)
            this.loadData();
        })           
    }
    /**
     * 下拉页面
     */
    onChangeSizePage = (value,page) => {
        this.setState({
           offset: 0,
           limit: page,
        }, () => {
            this.loadData()
        })
    }
    // eslint-disable-next-line
    render() {
        
        const {columns,data,id} = this.state
        const rowSelection = {
            onChange: this.onCheckeBox
        }
        return (
            <div>
                <div className="uuuu">                   
                    <div className="tttt">
                        <Form layout="inline" onFinish={this.onFinish}>
                            <Form.Item label="视频名" name="videoname">
                                <Input placeholder="请输入搜索的视频名" />
                            </Form.Item>    
                            <Form.Item>
                                <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                                    搜索
                                </Button>
                            </Form.Item>
                        </Form>
                    </div>
                </div>
                <Fragment >
                <div className="table-row">
                    <Table 
                    className="table-wrap"
                    //  pagination={{pageSize:10}}
                    pagination={false}
                    rowSelection={rowSelection} 
                    rowKey='id' 
                    columns={columns} 
                    dataSource={data} 
                    bordered>
                     </Table>
                     <hr color={'#f5f5f5'}/>
                    <Row  style={{marginTop:8}}>
                        <Col span={8}></Col>
                        <Col span={16}>
                            <Pagination 
                                onChange={this.onChangeCurrentPage}
                                onShowSizeChange={this.onChangeSizePage}
                                pageSize={this.state.limit}
                                className="pull-right"
                                defaultCurrent={1}
                                showSizeChanger
                                showQuickJumper
                                total={this.state.total} 
                                showTotal={total => `总计 ${this.state.total} 条` }//此处更改总页数防止，页面跳转时总页数为每页显示数量
                            />
                        </Col>
                    </Row>  
                </div>             
                </Fragment>   
                {/* 删除弹窗 */}
                <Modal
                title="提示"
                visible={this.state.visible}
                onOk={this.hideModal}
                onCancel={() => {this.setState({visible:false})}}
                okText="确认"
                cancelText="取消"
                >
                    <p className="text-center">确认删除此信息？<strong className="color-red">删除后将无法恢复。</strong></p>
                </Modal>

            </div>
        )
    }
}

